package com.visikard.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.visikard.application.Constant;
import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.GetTransactionHistoryCouponTask;
import com.visikard.item.ItemTransactionHistory;
import com.visikard.ui.R;
import com.visikard.ui.activity.TransactionHistoryActivity;
import com.visikard.ui.adapter.TransactionHistoryCouponAdapter;
import com.visikard.utility.Utils;
import com.visikard.widget.DatePickerFragment;
import com.visikard.widget.expandedlistview.ExpandingListView;

public class TransactionCouponKardFragment extends BaseFragment implements OnClickListener, SetTimeParent {

	private ExpandingListView listView;
	private TextView headerDateBack;
	private TextView headerDateNext;
	private ImageView imageDateBack, imageDateNext;

	private int pageIndex = 1;
	private boolean isNoLoadMore = false;
	private boolean isLoadingMore = false;

	private Context mContext;

	private static long TIME_MIN = 0;
	private static long TIME_MAX = 0;

	private ArrayList<ItemTransactionHistory> listItemTransaction;
	TransactionHistoryCouponAdapter transactionAdapter;

	private String mCurentBackDate, mCurentNextDate;

	private BaseTask mAsyncTask;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.transaction_coupon_kard_fragment, container, false);

		mContext = getActivity();

		TIME_MAX = Calendar.getInstance().getTimeInMillis();
		TIME_MIN = TIME_MAX;

		innit(view);

		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

		getListTrasaction();
	}

	private void innit(View view) {
		headerDateBack = (TextView) view.findViewById(R.id.transaction_date_start);
		headerDateNext = (TextView) view.findViewById(R.id.transaction_date_end);
		listView = (ExpandingListView) view.findViewById(R.id.list_transaction_history_coupon_kard);
		imageDateBack = (ImageView) view.findViewById(R.id.coupon_btn_date_back);
		imageDateNext = (ImageView) view.findViewById(R.id.coupon_btn_date_next);

		headerDateBack.setOnClickListener(this);
		headerDateNext.setOnClickListener(this);
		imageDateBack.setOnClickListener(this);
		imageDateNext.setOnClickListener(this);

		listView.setVisibility(View.GONE);

		String strDate = ((TransactionHistoryActivity) getActivity()).getDateToday();
		headerDateBack.setText(strDate);
		headerDateNext.setText(strDate);

		String strDateServer = ((TransactionHistoryActivity) getActivity()).getDateTodayServer();
		mCurentBackDate = strDateServer;
		mCurentNextDate = strDateServer;

		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

				// For load more
				if (totalItemCount > 2 && firstVisibleItem + visibleItemCount >= totalItemCount && !isLoadingMore
						&& !isNoLoadMore) {
					pageIndex++;
					isLoadingMore = true;
					mDataloadMore();
					// load more
				}
			}
		});

		// listView.setOnItemClickListener(this);
	}

	@Override
	public void onPause() {
		// ((MainHomeActivity)getActivity()).isShowProgress(false);
		// ((TransactionHistoryActivity) getActivity()).dismissProgressDialog();

		// if (mDataloadTransactions != null)
		// TaskExecuter.getInstance(getActivity()).cancel(
		// mDataloadTransactions);
		// if (mDataloadMoreTransactions != null)
		// TaskExecuter.getInstance(getActivity()).cancel(
		// mDataloadMoreTransactions);

		super.onPause();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {

		super.onSaveInstanceState(outState);
	}

	private void getListTrasaction() {
		mAsyncTask = new GetTransactionHistoryCouponTask(mHandler);

		// add time zone to server
		String searchBackDate = mCurentBackDate;
		String timeZone = Utils.getTimeZoneString();
		searchBackDate += " " + Constant.START_DATE_SEARCH;
		searchBackDate += timeZone;

		String searchNextDate = mCurentNextDate;
		searchNextDate += " "
				+ new SimpleDateFormat(Constant.TIME_SHORT_FORMAT_HHMMSS, Constant.DEFAULT_LOCALE).format(new Date());
		searchNextDate += timeZone;

		// mAsyncTask.execute(mCurentBackDate, mCurentNextDate, pageIndex);
		mAsyncTask.execute(VKRegApplication.uid, Constant.BOOLEAN_TRUE, searchBackDate, searchNextDate, pageIndex,
				VKRegApplication.mPageSize);
	}

	private void mDataloadMore() {
		mAsyncTask = new GetTransactionHistoryCouponTask(mHandler);

		// add time zone to server
		String searchBackDate = mCurentBackDate;
		String timeZone = Utils.getTimeZoneString();
		searchBackDate += " " + Constant.START_DATE_SEARCH;
		searchBackDate += timeZone;

		String searchNextDate = mCurentNextDate;
		// searchNextDate += " " + new
		// SimpleDateFormat(Constant.TIME_SHORT_FORMAT_HHMMSS,
		// Constant.DEFAULT_LOCALE).format(new Date());
		searchNextDate += " " + Constant.END_DATE_SEARCH;
		searchNextDate += timeZone;

		// mAsyncTask.execute(mCurentBackDate, mCurentNextDate, pageIndex);
		mAsyncTask.execute(VKRegApplication.uid, Constant.BOOLEAN_TRUE, searchBackDate, searchNextDate, pageIndex,
				VKRegApplication.mPageSize);
	}

	@Override
	public void setBackDate(int year, int month, int day) {
		String date = ((TransactionHistoryActivity) getActivity()).getMonth(month + 1) + " " + (day <= 9 ? " 0" : " ")
				+ day + ", " + year;
		String dateServer = year + (month + 1 <= 9 ? "-0" : "-") + (month + 1) + (day <= 9 ? "-0" : "-") + day;
		if (!dateServer.equals(mCurentBackDate)) {
			headerDateBack.setText(date);
			mCurentBackDate = dateServer;
			getListTrasaction();
		}
	}

	public void showBackDatePickerDialog() {
		DatePickerFragment newFragment = new DatePickerFragment();
		newFragment.setParent(this, TIME_MIN, TIME_MAX, false);
		newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
	}

	public void showNextDatePickerDialog() {
		DatePickerFragment newFragment = new DatePickerFragment();
		newFragment.setParent(this, TIME_MIN, TIME_MAX, true);
		newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
	}

	@Override
	public void setNextDate(int year, int month, int day) {
		String date = ((TransactionHistoryActivity) getActivity()).getMonth(month + 1) + " " + (day <= 9 ? " 0" : " ")
				+ day + ", " + year;
		String dateServer = year + (month + 1 <= 9 ? "-0" : "-") + (month + 1) + (day <= 9 ? "-0" : "-") + day;
		if (!dateServer.equals(mCurentNextDate)) {
			headerDateNext.setText(date);
			mCurentNextDate = dateServer;
			getListTrasaction();
		}
	}

	@Override
	public void setTimeMin(long timeMin, long timeMax) {
		TIME_MIN = timeMin;
		TIME_MAX = timeMax;
	}

	// get selected birthday
	@Override
	public String getBackdayStr() {
		return mCurentBackDate;
	}

	// get selected birthday
	@Override
	public String getNextdayStr() {
		return mCurentNextDate;
	}

	// @Override
	// public void onItemClick(AdapterView<?> parent, View view, int
	// position,long id) {
	// Animation slide = AnimationUtils.loadAnimation(getActivity(),
	// R.anim.activity_slide_out_bottom);
	// view.startAnimation(slide);
	// }

	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
			case UIMessage.MSG_GET_LIST_SUCCESS:
				if (!isLoadingMore) {
					listItemTransaction = (ArrayList<ItemTransactionHistory>) msg.obj;
					if (listItemTransaction == null)
						listItemTransaction = new ArrayList<ItemTransactionHistory>();
					if (listItemTransaction.size() < VKRegApplication.mPageSize)
						isNoLoadMore = true;
					if (listItemTransaction != null && listItemTransaction.size() > 0) {
						listView.setVisibility(View.VISIBLE);
						transactionAdapter = new TransactionHistoryCouponAdapter(mContext, listItemTransaction,
								mHandler);
						listView.setAdapter(transactionAdapter);
						transactionAdapter.notifyDataSetChanged();
					}
					else
						listView.setVisibility(View.GONE);
				}
				else {
					List<ItemTransactionHistory> listResults = (ArrayList<ItemTransactionHistory>) msg.obj;
					listItemTransaction.addAll(listResults);
					transactionAdapter.notifyDataSetChanged();
				}

				isLoadingMore = false;
				return true;
				// case TransactionHistoryActivity.MSG_OPEN_TRASACTIONS_DEATIL:
				// if(listItemTransaction.size() > 0 &&
				// listItemTransaction.get(msg.arg1) != null){
				// Intent intent = new Intent(getActivity(),
				// TransactionDetailSpecialsKardActivity.class);
				// intent.putExtra(TransactionDetailSpecialsKardActivity.MSG_ITEM_REDEEM_KARD_TRANSACTION,
				// listItemTransaction.get(msg.arg1));
				// intent.putExtra(TransactionDetailSpecialsKardActivity.MSG_IS_COUPON_KARD,
				// true);
				// startActivity(intent);
				// getActivity().overridePendingTransition(R.anim.anim_slide_in_from_right,
				// R.anim.anim_slide_out_from_right);
				// }
				// break;
		}
		return super.handleMessage(msg);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.coupon_btn_date_back:
			case R.id.transaction_date_start:
				showBackDatePickerDialog();
				break;
			case R.id.coupon_btn_date_next:
			case R.id.transaction_date_end:
				showNextDatePickerDialog();
				break;
			default:
				break;
		}
	}

}
